package com.zuimei.zuimei.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Jogger on 2017/1/23.
 */

public class URLImageGetter implements Html.ImageGetter {
    TextView textView;
    Context context;

    public URLImageGetter(Context contxt, TextView textView) {
        this.context = contxt;
        this.textView = textView;
    }

    @Override
    public Drawable getDrawable(String paramString) {
        URLDrawable urlDrawable = new URLDrawable(context);;
        //开启异步加载图片
        ImageGetterAsyncTask getterTask = new ImageGetterAsyncTask(urlDrawable);
        getterTask.execute(paramString);
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable urlDrawable) {
            this.urlDrawable = urlDrawable;
        }

        @Override
        protected void onPostExecute(Drawable result) {
            if (result != null) {
              urlDrawable.drawable = result;
                //设置图片宽高
                int width = ScreenUtil.getSrceenWidth(context) - 60;
                int height = (int) (width / ((float) result.getIntrinsicWidth() / result
                        .getIntrinsicHeight()));
                urlDrawable.drawable.setBounds(30, 0, width, height);
                //URLImageGetter.this.textView.requestLayout();
                textView.invalidate();
                textView.setText(textView.getText());
             }
           // textView.setText(Html.fromHtml());
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        public Drawable fetchDrawable(String url) {
            Drawable drawable = null;
            HttpURLConnection connection = null;
            InputStream is = null;
            try {
                connection = (HttpURLConnection) new URL(url).openConnection();
                is = connection.getInputStream();
                drawable = Drawable.createFromStream(is, "");
                //return drawable;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return drawable;
        }
    }
}
